package cc.sjfx.sharedoc.activity.user;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.mandroid.frame.toast.MToast;
import cn.mandroid.frame.tools.MD5;
import cc.sjfx.sharedoc.R;
import cc.sjfx.sharedoc.activity.BasicActivity;
import cc.sjfx.sharedoc.bmob.SessionToken;
import cc.sjfx.sharedoc.db.bmob.Province;
import cc.sjfx.sharedoc.db.bmob.School;
import cc.sjfx.sharedoc.db.bmob.User;
import cc.sjfx.sharedoc.dialog.MyDialog;
import cc.sjfx.sharedoc.function.ReadAndWriteFile;
import cc.sjfx.sharedoc.utils.CheckUtils;
import cc.sjfx.sharedoc.utils.StrUtils;
import cc.sjfx.sharedoc.widget.anotation.ViewInject;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class UserRegisterActivity extends BasicActivity implements
		OnClickListener, OnItemSelectedListener {
	@ViewInject(id = R.id.phoneEdit)
	private EditText phoneEdit;
	@ViewInject(id = R.id.passwordEdit)
	private EditText passwordEdit;
	@ViewInject(id = R.id.setSchoolEdit)
	private EditText setSchoolEdit;
	@ViewInject(id = R.id.rePassEdit)
	private EditText rePassEdit;
	@ViewInject(id = R.id.loginText)
	private TextView loginText;
	@ViewInject(id = R.id.regBut)
	private Button regBut;
	@ViewInject(id = R.id.nickEdit)
	private EditText nickEdit;
	private Spinner provinceSpinner;
	private Spinner schoolSpinner;
	private Button dialog_submit, dialog_cancle;
	String phone;
	String password;
	String nick;
	MyDialog myDialog;
	int school = 0;
	String[] provinces;
	int[] pid;
	String[] schools;
	int[] sid;
	int sidCache = 0;
	String schoolName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_register);
		setExitActivityMap(StrUtils.EXIT_ACTIVITY_LOGINANDREG, this);
		init();
	}

	private void init() {
		// TODO Auto-generated method stub
		regBut.setOnClickListener(this);
		loginText.setOnClickListener(this);
		setSchoolEdit.setOnClickListener(this);
		setTitle("注册");
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.regBut:
			password = passwordEdit.getText().toString();
			nick = nickEdit.getText().toString();
			if (!password.equals(rePassEdit.getText().toString())) {
				MToast.show(this, "两次密码输入有误");
				break;
			}
			phone = phoneEdit.getText().toString().trim();
			if (!CheckUtils.passIsValid(password)) {
				MToast.show(this, "密码输入有误");
			} else if (school == 0) {
				MToast.show(this, "请选择学校");
			} else if (!CheckUtils.phoneIsValid(phone)) {
				MToast.show(this, "手机号码或邮箱输入有误");
			} else if (nick.length() >= 7) {
				MToast.show(this, "昵称最多不超过6个字符");
			} else {
				BmobQuery<User> query = new BmobQuery<User>();
				query.addWhereEqualTo("nickName", nick);
				query.findObjects(context, new FindListener<User>() {

					@Override
					public void onError(int arg0, String arg1) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(List<User> arg0) {
						// TODO Auto-generated method stub
						if (arg0.size() == 0) {
							doRegister(phone, password);
						} else {
							MToast.show(context, "昵称已被使用");
						}
					}
				});
			}
			// if (CheckUtils.passIsValid(password)
			// && CheckUtils.phoneIsValid(phone)&&school!=0) {
			// doRegister(phone, password);
			// } else if (!CheckUtils.passIsValid(password)) {
			// MToast.show(this, "密码输入有误");
			// } else if(school==0){
			// MToast.show(this, "请选择学校");
			// }else {
			// MToast.show(this, "手机号码或邮箱输入有误");
			// }
			break;
		case R.id.loginText:
			startActivity(null, UserLoginActivity.class);
			break;
		case R.id.setSchoolEdit:
			setSchool();
			break;
		default:
			break;
		}
	}

	private void setSchool() {
		// TODO Auto-generated method stub
		if (dialog_submit == null) {
			OnClickListener dialog_click = new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					switch (v.getId()) {
					case R.id.button1:
						school = sidCache;
						setSchoolEdit.setText(schoolName);
						myDialog.dismiss();
						break;
					case R.id.button2:
						myDialog.dismiss();
						break;
					default:
						break;
					}
				}
			};
			myDialog = new MyDialog(context, R.layout.dialog_setschool);
			schoolSpinner = (Spinner) myDialog.findViewById(R.id.schoolSp);
			provinceSpinner = (Spinner) myDialog.findViewById(R.id.provinceSp);
			spinnerInit();
			dialog_submit = (Button) myDialog.findViewById(R.id.button1);
			dialog_cancle = (Button) myDialog.findViewById(R.id.button2);
			dialog_submit.setOnClickListener(dialog_click);
			dialog_cancle.setOnClickListener(dialog_click);
			schoolSpinner.setOnItemSelectedListener(this);
			provinceSpinner.setOnItemSelectedListener(this);
		}

		myDialog.show();
	}

	private void spinnerInit() {
		// TODO Auto-generated method stub
		final ReadAndWriteFile file = new ReadAndWriteFile(context);
		String data = file.readFile(StrUtils.PROVINCE_FILE);
		if (data.equals("")) {
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
					android.R.layout.simple_spinner_item,
					new String[] { "正在加载……" });
			provinceSpinner.setAdapter(adapter);
			BmobQuery<Province> query = new BmobQuery<Province>();
			query.setLimit(50);
			query.findObjects(context, new FindListener<Province>() {
				@Override
				public void onSuccess(List<Province> arg0) {
					// TODO Auto-generated method stub
					JSONArray jsonArray = new JSONArray();
					for (int i = 0; i < arg0.size(); i++) {
						JSONObject jsonObject = new JSONObject();
						try {
							jsonObject.put("name", arg0.get(i).getName());
							jsonObject.put("pid", arg0.get(i).getPid());
							jsonArray.put(jsonObject);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					file.writeFile(StrUtils.PROVINCE_FILE, jsonArray.toString());
					spinnerInit();
				}

				@Override
				public void onError(int arg0, String arg1) {
					// TODO Auto-generated method stub

				}
			});
		} else {
			try {
				JSONArray jsonArray = new JSONArray(data);
				int len = jsonArray.length();
				provinces = new String[len + 1];
				pid = new int[len + 1];
				provinces[0] = "请选择";
				pid[0] = 0;
				for (int i = 0; i < len; i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					provinces[i + 1] = jsonObject.getString("name");
					pid[i + 1] = jsonObject.getInt("pid");
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
					android.R.layout.simple_spinner_item, provinces);
			provinceSpinner.setAdapter(adapter);
		}
	}

	private void doRegister(final String phone, final String password) {
		// TODO Auto-generated method stub
		User user = new User();
		user.setPassword(MD5.getMd5Code(password));
		user.setSchool(schoolName);
		user.setSid(school);
		user.setUsername(phone);
		user.setNickName(nick);
		if (phone.contains("@")) {
			user.setEmail(phone);

		} else {

			user.setMobilePhoneNumber(phone);
		}
		user.signUp(context, new SaveListener() {
			@Override
			public void onSuccess() {
				// TODO Auto-generated method stub
				MToast.show(context, "注册成功");
				SessionToken.update(context);
				exitMap(StrUtils.EXIT_ACTIVITY_LOGINANDREG);
			}

			@Override
			public void onFailure(int code, String msg) {
				// TODO Auto-generated method stub
				switch (code) {
				case 202:
					MToast.show(context, "手机号码已存在");
					break;
				case 203:
					MToast.show(context, "邮箱已存在");
					break;
				default:
					break;
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.user_register, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.provinceSp:
			if (arg2 != 0) {
				getSchool(pid[arg2]);
			}
			break;
		case R.id.schoolSp:
			if (sid != null) {
				sidCache = sid[arg2];
				schoolName = schools[arg2];
			}

			break;
		default:
			break;
		}
	}

	private void getSchool(final int pid) {
		// TODO Auto-generated method stub
		final ReadAndWriteFile file = new ReadAndWriteFile(context);
		String data = file.readFile(StrUtils.SCHOOL_FILE + pid);
		if (CheckUtils.stringIsNull(data)) {
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
					android.R.layout.simple_spinner_item,
					new String[] { "正在加载……" });
			schoolSpinner.setAdapter(adapter);
			BmobQuery<School> query = new BmobQuery<School>();
			query.addWhereEqualTo("place", pid);
			query.setLimit(200);
			query.findObjects(context, new FindListener<School>() {
				@Override
				public void onError(int arg0, String arg1) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onSuccess(List<School> arg0) {
					// TODO Auto-generated method stub
					JSONArray jsonArray = new JSONArray();
					for (int i = 0; i < arg0.size(); i++) {
						JSONObject jsonObject = new JSONObject();
						try {
							jsonObject.put("name", arg0.get(i).getName());
							jsonObject.put("sid", arg0.get(i).getSid());
							jsonArray.put(jsonObject);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					file.writeFile(StrUtils.SCHOOL_FILE + pid,
							jsonArray.toString());
					getSchool(pid);
				}
			});
		} else {
			try {
				JSONArray jsonArray = new JSONArray(data);
				int len = jsonArray.length();
				sid = new int[len];
				schools = new String[len];
				for (int i = 0; i < len; i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);
					sid[i] = jsonObject.getInt("sid");
					schools[i] = jsonObject.getString("name");
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
					android.R.layout.simple_spinner_item, schools);
			schoolSpinner.setAdapter(adapter);
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub

	}

}
